Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
I get the " Cannot set headers after they are sent to the client " error with node-js

I'm coding the backend of a wbesite for a school project, and i got an error in the likes and dislikes part of my code. I get the " Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client" when i try to remove like but when i use promises instead of async in my removeLike function it's working.

    async function likeSauce(req, res) {
    if (![1, -1, 0].includes(req.body.like)) {
        return res.status(403).send({ message: "Invalid like value" })
    } else {
        await addLike(req, res)
        await addDislike(req, res)
        await removeLike(req, res)
        await removeDislike(req, res)
    }
}


async function addLike(req, res) {
    if (req.body.like === 1) {
        try {
            await Product.findOneAndUpdate({ _id: req.params.id }, { $inc: { likes: 1 }, $push: { usersLiked: req.body.userId } })
            return res.status(200).send({ message: "Like added !" })
        } catch (error) {
            res.status(400).send({ error })
        }
    }
}

async function addDislike(req, res) {
    if (req.body.like === -1) {
        try {
            await Product.findOneAndUpdate({ _id: req.params.id }, { $inc: { dislikes: 1 }, $push: { usersDisliked: req.body.userId } })
            return res.status(200).send({ message: "Dislike added !" })
        } catch (error) {
            res.status(400).send({ error })
        }
    }
}


async function removeLike(req, res) {
    const resultat = await Product.findOne({ _id: req.params.id })
    if (resultat.usersLiked.includes(req.body.userId)) {
        try {
            await Product.findOneAndUpdate({ _id: req.params.id }, { $inc: { likes: -1 }, $pull: { usersLiked: req.body.userId } })
            return res.status(200).send({ message: "Like removed !" })
        } catch (error) {
            res.status(400).send({ error })
        }
    }
}

async function removeDislike(req, res) {
    const resultat = await Product.findOne({ _id: req.params.id })
    if (resultat.usersDisliked.includes(req.body.userId)) {
        try {
            await Product.findOneAndUpdate({ _id: req.params.id }, { $inc: { dislikes: -1 }, $pull: { usersDisliked: req.body.userId } })
            return res.status(200).send({ message: "Dislike removed !" })
        } catch (error) {
            res.status(400).send({ error })
        }
    }
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

That's because you use await for:

await addLike(req, res)
await addDislike(req, res)
await removeLike(req, res)
await removeDislike(req, res)

This will instruct node.js to wait for functions completions, but in all of theses functions, you return with a res.send.

So after, the first call Express has already send the response, and second function call will générate your error while trying to res.send

You must take advantage of Node.js aysnchronous bay using callbak or better promise.

You should res.send only once.

promisify your 4 functions and use then() and catch() to call them. And then call res.send only once in the last then().

Also, you should test like value before calling functions, doing this you will not call all function, but just the right one.

about 4 years ago · Juan Pablo Isaza Relatório

0

Always do return res, even in catch section

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda